package com.gs.cd.cloud.start.utils;


import com.gs.cd.api.HttpHeadersParam;
import com.gs.cd.utils.jwt.JwtUserInfo;
import com.gs.cd.utils.jwt.JwtUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * create by hippo  2020/6/8
 *
 * @Description
 **/
public class HttpHeadersParamUtils {

    public static String getAppId() {
        return getAppId(getHttpServletRequest());
    }

    public static String getAppId(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        return request.getHeader(HttpHeadersParam.APP_ID);
    }

    public static String getToken() {
        return getToken(getHttpServletRequest());
    }

    public static String getToken(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String token = request.getHeader(HttpHeadersParam.TOKEN);
        return token;
    }


    public static String getTenantCode(HttpServletRequest request) {
        return request.getHeader(HttpHeadersParam.TENANT_CODE);
    }

    public static String getTenantCode() {
        return getTenantCode(getHttpServletRequest());
    }

    public static JwtUserInfo getJwtUserInfo(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String token = getToken(request);
        return JwtUtils.getJwtUserInfo(token);
    }

    public static JwtUserInfo getJwtUserInfo() {
        return JwtUtils.getJwtUserInfo(getToken());
    }


    public static ServletRequestAttributes getServletRequestAttributes() {
//        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes());
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
    }

    public static HttpServletRequest getHttpServletRequest() {
        ServletRequestAttributes attributes = getServletRequestAttributes();
        if (attributes == null) {
            return null;
        }

        return attributes.getRequest();
    }
}